package com.ysx.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysx.common.utils.AppJwtUtil;
import com.ysx.user.dto.LoginDto;
import com.ysx.user.mapper.ApUserMapper;
import com.ysx.user.pojo.ApUser;
import com.ysx.user.service.ApUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2021-09-08
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public Map<String, Object> login(LoginDto appUser) {
        //根据用户名获取到用户信息
        QueryWrapper<ApUser> querywrapper = new QueryWrapper<ApUser>() ;
        querywrapper.eq("phone",appUser.getPhone());
        //获取到数据库中的用户
        ApUser user = apUserMapper.selectOne(querywrapper);
        //再获取用户表中的盐值
        if(user==null){
            return null;
        }
        String salt = user.getSalt();
        String password = DigestUtils.md5DigestAsHex((appUser.getPassword() + salt).getBytes());
        //传递过来的密码和数据库中的密码进行匹配
        if(!password.equals(user.getPassword())){
            return null;
        }
        //登录成功
        Map<String,Object> info = new HashMap<>();
        String token = AppJwtUtil.createToken(user.getId().longValue());
        info.put("token",token);
        //密码不要设置
        user.setPassword("");
        info.put("user",user);
        return info;
    }
}
